package com.icangya.service.impl;

import com.icangya.DAO.IBannersDAO;
import com.icangya.domain.Banners;
import com.icangya.service.IBannerManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;

@Service("BannerManageServiceImpl")
public class BannerManageServiceImpl implements IBannerManageService{


    @Autowired
    private IBannersDAO iBannersDAO;


    @Override
    public List<Banners> getAllBanner() {
    return iBannersDAO.getAllBanners();
    }

    @Override
    public void saveNewBanner( HttpServletRequest request, MultipartFile file) {


        //上传的目录地址
        String uploadDir= request.getSession().getServletContext().getRealPath("/")+"upload/shop/carouse/";
        //如果目录不存在，自动创建文件夹
        File dir=new File(uploadDir);
        if(!dir.exists()){
            dir.mkdir();
        }
        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传文件名
        String filename= UUID.randomUUID()+suffix;

        //服务器端保存的文件对象
        File serverFile=new File(uploadDir+filename);

        //将上传的文件写入到服务器端文件内
        try {
            file.transferTo(serverFile);
            request.getSession().setAttribute("carPic","upload/shop/carouse/"+filename);
        } catch (IOException e) {
            e.printStackTrace();
            request.getSession().setAttribute("carPic","");
        }
    }


    @Override
    public Serializable saveToSql(String path) {
        if(path==null||path.equals("")){return -1;}
        Banners bn=new Banners(path);

        return iBannersDAO.save(bn);
    }


    @Override
    public boolean deleteIt(long id) {
        Banners bn=iBannersDAO.getByid(id);
        if(bn==null){
            return false;
        }
        return iBannersDAO.deleteBanner(bn);

    }
}
